package com.yycx.module.bus.provider.handler.haiying.tasktodo.order;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.provider.service.BusPaymentService;
import com.yycx.module.bus.provider.service.hy.HyOrderDetailService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单审批结束监听器
 *
 * @author zyf
 */
@Component
@Slf4j
@DSTransactional
public class HyOrderProcessEndListener implements ExecutionListener {
    @Resource
    private HyOrderService orderService;

    @Resource
    private HyOrderDetailService orderDetailService;

    @Resource
    private BusPaymentService paymentService;

    @Override
    @DSTransactional
    public void notify(DelegateExecution delegateExecution) {
        try {
            //获取业务主键
            String businessKey = delegateExecution.getProcessInstanceBusinessKey();
            HyOrder order = orderService.getById(businessKey);
            String orderId = order.getOrderId();
            Integer sendType = order.getSendType();
            boolean tag = true;
            if (tag) {
                //现款方式
                if (sendType.equals(SendTypeEnum.XK.getCode())) {
                    //更新认款单为已认款状态
                    paymentService.updatePaymentState(businessKey, CommonConstants.INT_2);
                }
                //资信认款
                if (sendType.equals(SendTypeEnum.ZBJ.getCode())) {
                    paymentService.updatePaymentState(businessKey, CommonConstants.INT_2);
                    List<BusPayment> paymentList = paymentService.selectByOrderIdAndAmountType(businessKey, AmountTypeEnum.CustomBond, CommonConstants.INT_2);
                    if (FlymeUtils.isNotEmpty(paymentList)) {
                        orderDetailService.updateCustomBond(paymentList.get(0));
                    }
                }
                orderService.updateOrderState(orderId, CommonConstants.INT_2);
            }
        } catch (Exception e) {
            log.error("#################订单审批结束异常#############");
            e.printStackTrace();
        }
    }

}
